package com.know.web;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.ServletException;

import org.apache.commons.lang.StringUtils;

import com.know.entity.Users;
import com.know.entity.Comments;
import com.know.service.CommentService;
import com.kzw.bean.Record;
import com.kzw.dao.support.Page;
import com.kzw.json.Jackson;

import my.mvc.RequestContext;
import my.util.ResponseUtils;

public class CommentAction {

	private CommentService commentService =new CommentService();
	
	/**
	 * 
	 * 读取评论列表(根据文章读取）
	 */
	public void list(RequestContext rc) throws ServletException, IOException {
		int pageNo = rc.param("page", 1);
		int pageSize = rc.param("limit", 15);
		String orderBy = rc.param("orderBy", "");
		String orderDir = rc.param("orderDir", "");
		long article_id=Long.parseLong(rc.param("id"));
		Page<Comments> page = new Page<>(pageNo, pageSize);
		if(StringUtils.isNotBlank(orderBy)) {
			page.setOrderBy(orderBy);
			page.setOrder(orderDir);
		}
		
		Record record = commentService.findPage(page,article_id);
		// 输出JSON
		String json = Jackson.me().toJson(record);
		//System.out.println(json);
		ResponseUtils.renderJson(rc.response(), json);
		
	}
	/**
	 * 读取最新评论
	 */
	public void newlist(RequestContext rc) throws ServletException, IOException {
		 List<Comments> list=commentService.newlist();

			// 输出JSON
			String json = Jackson.me().with(Users.class, "user_name").toJson(list);
			//System.out.println(json);
			ResponseUtils.renderJson(rc.response(), json);
		
	}
	/**
	 * 留言提交（留言墙默认传来文章ID为0 ）
	 */
	public void padd(RequestContext rc) throws ServletException, IOException {
		Comments comment=rc.form(Comments.class);
		Record record=new Record(false);
		if(comment!=null)
		{
			commentService.save(comment);
			record.setSuccess(true);
			
		}
		
		record.setMsg("成功提交");
		String json=Jackson.me().toJson(record);
		ResponseUtils.renderJson(rc.response(), json);
	}

}
